/*************************************************************************
    > File Name: cp.c
    > Author: Xing.Dai
    > Mail: Xing.Dai@aliyun.com 
    > Created Time: 2017-05-12 23:38
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

#define BUFFER_SIZE	4096
#define COPY_MODE	0644

/**
 * @Synopsis  
 *
 * @Param s1
 * @Param s2
 */
void oops(char *s1, char *s2)
{
	fprintf(stderr, "Error: %s.", s1);
	perror(s2);

	exit(1);
}

/**
 * @Synopsis  
 *
 * @Param argc
 * @Param args
 *
 * @Returns   
 */
int main(int argc, char **args)
{
	int in_fd, out_fd, n_chars;
	char buf[BUFFER_SIZE];

	if(argc != 3){
		fprintf(stderr, "usage: %s source destination.\n", *args);
		exit(1);
	}
	
	if((in_fd = open(args[1], O_RDONLY)) == -1){
		oops("Cannot open ", args[1]);
	}

	if((out_fd = creat(args[2], COPY_MODE)) == -1){
		oops("Cannot create ", args[2]);
	}

	while((n_chars = read(in_fd, buf, BUFFER_SIZE)) > 0){
		if(write(out_fd, buf, n_chars) != n_chars)
			oops("Write error to ", args[2]);
	}
	
	if(n_chars == -1){
		oops("Read error from ", args[1]);
	}

	if(close(in_fd) == -1 || close(out_fd) == -1){
		oops("Error closing files.", "");
	}

	return 0;
}
